package com.coollang.smartbra.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.eventbus.CommonEvent;
import com.coollang.smartbra.utils.LogUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jeesoft.widget.pickerview.LoopListener;
import cn.jeesoft.widget.pickerview.LoopView;
import de.greenrobot.event.EventBus;

import static com.coollang.smartbra.R.id.pv_day;
import static com.coollang.smartbra.R.id.pv_month;
import static com.coollang.smartbra.R.id.pv_year;

/**
 * Created by Administrator on 2016/11/8 0008.
 */

public class SetWeelDialog extends Dialog implements View.OnClickListener {

    private final String type;
    private final Context context;
    private String year;
    private String month;
    private String day;
    @BindView(R.id.tv_pick_cancel)
    TextView tvPickCancel;
    @BindView(R.id.tv_pick_confirm)
    TextView tvPickConfirm;
    @BindView(R.id.picklerview)
    LoopView picklerview;
    @BindView(R.id.tv_bmp_unit)
    TextView tvBmpUnit;
    @BindView(R.id.rl_wh)
    RelativeLayout rlWh;
    @BindView(R.id.ll_pick)
    LinearLayout llPick;
    @BindView(pv_year)
    LoopView pvYear;
    @BindView(pv_month)
    LoopView pvMonth;
    @BindView(pv_day)
    LoopView pvDay;
    @BindView(R.id.rl_birthday)
    RelativeLayout rlBirthday;
    private int startNub;
    private int endNub;

    private int indexYear = -1; // 选中的年的下标
    private int indexMonth = -1;
    private int indexDay = -1;
    private int currentYear;
    private int currentMonth;
    private int currentDay;
    private List<String> yearList;
    private List<String> monthList;
    private List<String> dayList;

    public SetWeelDialog(Context context, String type, String year, String month, String day) {
        super(context, R.style.dialog);
        this.type = type;
        this.context = context;
        this.year = year; // 服务器中保存的日期（生日）
        this.month = month;
        this.day = day;
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        String time[] = df.format(date).split("-");
        currentYear = Integer.parseInt(time[0]);
        currentMonth = Integer.parseInt(time[1]);
        currentDay = Integer.parseInt(time[2]);
    }

    @Override
    public void show() {
        Window window = this.getWindow();
        window.setWindowAnimations(R.style.dialog_enter_exit); // 添加动画
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        window.getDecorView().setPadding(0, 0, 0, 0);
        // 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        this.onWindowAttributesChanged(lp);
        window.setGravity(Gravity.BOTTOM);// 居底
        // 设置点击外围解散
        this.setCanceledOnTouchOutside(true);
        super.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_set_weel);
        ButterKnife.bind(this);
        if (type.equals(Constants.TYPE_SETDATE)) {
            rlBirthday.setVisibility(View.VISIBLE);
            rlWh.setVisibility(View.GONE);
            initData();
        } else {
            rlBirthday.setVisibility(View.GONE);
            rlWh.setVisibility(View.VISIBLE);
            initView();
            showPickView();
        }
    }


    //***************************************生日***************************************************//
    private void setDay() {
        if (Integer.parseInt(year) == currentYear && Integer.parseInt(month) == currentMonth) {
            for (int i = 1; i <= currentDay; i++) {
                dayList.add(String.valueOf(i));
                if (i == Integer.parseInt(day)) {
                    indexDay = i - 1;
                }
            }
        } else {
            if (Integer.parseInt(month) == 2) {
                // 判断是否是闰年
                if (Integer.parseInt(year) % 400 == 0 || (Integer.parseInt(year) % 100 != 0 && Integer.parseInt(year) % 4 == 0)) {
                    dayList.clear();
                    for (int i = 1; i <= 29; i++) {
                        dayList.add(String.valueOf(i));
                        if (i == Integer.parseInt(day)) {
                            indexDay = i - 1;
                        }
                    }
                } else {
                    dayList.clear();
                    for (int i = 1; i <= 28; i++) {
                        dayList.add(String.valueOf(i));
                        if (i == Integer.parseInt(day)) {
                            indexDay = i - 1;
                        }
                    }
                }
            } else if (Integer.parseInt(month) == 4 || Integer.parseInt(month) == 6 || Integer.parseInt(month) == 9 || Integer.parseInt(month) == 11) {
                dayList.clear();
                for (int i = 1; i <= 30; i++) {
                    dayList.add(String.valueOf(i));
                    if (i == Integer.parseInt(day)) {
                        indexDay = i - 1;
                    }
                }
            } else {
                dayList.clear();
                for (int i = 1; i <= 31; i++) {
                    dayList.add(String.valueOf(i));
                    if (i == Integer.parseInt(day)) {
                        indexDay = i - 1;
                    }
                }
            }
        }
    }

    private void setMonth() {
        if (Integer.parseInt(year) == currentYear) {
            indexMonth = 0;
            monthList.clear();
            for (int i = 1; i <= currentMonth; i++) {
                monthList.add(String.valueOf(i));
            }
        } else {
            monthList.clear();
            for (int i = 1; i < 13; i++) {
                monthList.add(String.valueOf(i));
                if (i == Integer.parseInt(month)) {
                    indexMonth = i - 1;
                }
            }
        }
    }

    private void initData() {
        yearList = new ArrayList<String>();
        monthList = new ArrayList<String>();
        dayList = new ArrayList<String>();
        for (int i = 1917; i <= currentYear; i++) {
            yearList.add(String.valueOf(i));
            // 判断服务器的年是不是i,如果是则将该下标保存
            if (i == Integer.parseInt(year)) {
                indexYear = i - 1917;
            }
        }
        setMonth();
        setDay();
        // 给滚动下标设置数据
        pvYear.setArrayList(yearList);
        pvMonth.setArrayList(monthList);
        pvDay.setArrayList(dayList);

        // 给滚动下标设置默认选中数据的下标
        if (indexYear != -1) {
            pvYear.setCurrentItem(indexYear);
        }
        if (indexMonth != -1) {
            pvMonth.setCurrentItem(indexMonth);
        }
        if (indexDay != -1) {
            pvDay.setCurrentItem(indexDay);
        }
        pvYear.setNotLoop(); // 不循环
        pvMonth.setNotLoop(); // 不循环
        pvDay.setNotLoop(); // 不循环
        pvYear.setMiddleAppleColor();
        pvYear.setMiddleLineVisible(false);
        pvMonth.setMiddleAppleColor();
        pvMonth.setMiddleLineVisible(false);
        pvDay.setMiddleAppleColor();
        pvDay.setMiddleLineVisible(false);
        pvYear.setListener(new LoopListener() {
            @Override
            public void onItemSelect(int item) {
                LogUtils.i("LoopView", String.valueOf(item));
                // text自定义滚动控件中显示选中的内容
                year = yearList.get(item);
                onYearChanged(year);
            }
        });

        pvMonth.setListener(new LoopListener() {
            @Override
            public void onItemSelect(int item) {
                // text自定义滚动控件中显示选中的内容
                month = monthList.get(item);
                onMonthChanged(month);
            }
        });

        pvDay.setListener(new LoopListener() {
            @Override
            public void onItemSelect(int item) {
                // text自定义滚动控件中显示选中的内容
                day = dayList.get(item);
            }
        });
    }

    private void onYearChanged(String year) {
        setMonth();
        pvMonth.setArrayList(monthList);
        pvMonth.setCurrentItem(indexMonth);
        pvMonth.invalidate();

        setDay();
        pvDay.setArrayList(dayList);
        if (indexDay != -1) {
            pvDay.setCurrentItem(indexDay);
        } else {
            pvDay.setCurrentItem(0);
        }
        pvDay.invalidate();
    }

    private void onMonthChanged(String month) {
        setDay();
        pvDay.setArrayList(dayList);
        if (indexDay != -1) {
            pvDay.setCurrentItem(indexDay);
        } else {
            pvDay.setCurrentItem(0);
        }
        pvDay.invalidate();
    }

    //***************************************************身高 体重*************************************//
    private void initView() {
        if (type.equals(Constants.TYPE_SETHEIGHT)) {
            startNub = 50;
            endNub = 251;
            firstIndex = 68;
            tvBmpUnit.setText(context.getString(R.string.unit_cm));
        } else if (type.equals(Constants.TYPE_SETWEIGHT)) {
            startNub = 10;
            endNub = 200;
            firstIndex = 28;
            tvBmpUnit.setText(context.getString(R.string.unit_kg));
        }

    }

    private List<String> dataList = new ArrayList<>();
    private int firstIndex = -1;
    private String originalData;
    private String wheelData;

    /**
     * 显示选项卡
     */
    private void showPickView() {
        for (int i = startNub; i < endNub; i++) {
            dataList.add(i + "");
            if (originalData != null && String.valueOf(i).equals(originalData)) {
                firstIndex = i - startNub;
            }
        }
        picklerview.setMiddleAppleColor();
        picklerview.setNotLoop();
        picklerview.setMiddleLineVisible(false);
        picklerview.setArrayList(dataList);
        if (firstIndex != -1) {
            picklerview.setCurrentItem(firstIndex);
        }
    }

    @OnClick({R.id.tv_pick_cancel, R.id.tv_pick_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pick_cancel:
                this.dismiss();
                break;
            case R.id.tv_pick_confirm:
                if (type.equals(Constants.TYPE_SETHEIGHT)) {
                    EventBus.getDefault().post(new CommonEvent(dataList.get(picklerview.getCurrentItem()) + "", CommonEvent.REQUESTSUEECCD, CommonEvent.SETHEIGHT));
                } else if (type.equals(Constants.TYPE_SETWEIGHT)) {
                    EventBus.getDefault().post(new CommonEvent(dataList.get(picklerview.getCurrentItem()) + "", CommonEvent.REQUESTSUEECCD, CommonEvent.SETWEIGHT));
                } else {
                    if (!yearList.get(pvYear.getCurrentItem()).equals(year)) {
                        year = yearList.get(pvYear.getCurrentItem());
                        onYearChanged(year);
                    }
                    if (!monthList.get(pvMonth.getCurrentItem()).equals(month)) {
                        month = monthList.get(pvMonth.getCurrentItem());
                        onMonthChanged(month);
                    }
                    if (!dayList.get(pvDay.getCurrentItem()).equals(day)) {
                        day = dayList.get(pvDay.getCurrentItem());
                    }
                    EventBus.getDefault().post(new CommonEvent(year + "-" + month + "-" + day, CommonEvent.REQUESTSUEECCD, CommonEvent.SETDATE));
                }
                this.dismiss();
                break;
        }
    }
}
